<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/common/includes.jsp" %>

<jsp:useBean id="nowDate" class="java.util.Date" />
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title></title>
	<!-- import css and js --> 
	<%@ include file="/common/metaInput.jsp" %>  
	<script src="${ctx}/js/jsp/comm.js" type="text/javascript"></script>
	<script type="text/javascript" src="${ctx}/js/My97DatePicker/WdatePicker.js"></script>
	<script type="text/javascript" src="${ctx}/js/jsp/yd/logic/ItemStateData.js"></script>
<script type="text/javascript">
var basic_Url="${ctx}/yd/logic/soreturn";
var grid;
var ItemStateList = ItemStateData.Rows;
var url;
$(function(){
	
	//表格结构
	grid = $("#table1").ligerGrid({
        columns: [
			{ display: '操作',width: 30,
			    render: function (record, rowindex, value, column) {
			    	var rc = JSON.stringify(record);
				  	  if(record.openBatch=='Y'){
				  		 return "<a href='javascript:ItemWindow("+rc+","+rowindex+")'><img src='${ctx}/js/ligerUI/skins/icons/add.gif' alt='添加' /></a>";
				  	  }else{
				  		 return "<h1>+</h1>";
				  	  }
					  }},
				  { display: 'id', name: 'id', width: 1 ,hide:true},
				  { display: '<font color="gray">产品编码</font>', name: 'prodNo', width: 120,
					  render: function (record, rowindex, value, column) {
						  var rc = JSON.stringify(record);
						  if(record.openBatch=='Y'){
							  return "<a href='javascript:ItemWindow("+rc+","+rowindex+")'>"+record.prodNo+"</a>";
						  	  }else{
						  		 return record.prodNo;
						  	  }
					  	  
					  }},
                  { display: '<font color="gray">产品名称</font>', name: 'prodName', width: 150 },
                  { display: '<font color="gray">型号规格</font>', name: 'prodSpecDesc', width: 150},
                  { display: '<font color="gray">物料是否可用批次</font>', name: 'openBatch' ,hide:true,width: 150, render: function (item, rowindex, value, column)
      			    {
              	   	if(item.openBatch=="Y"){
              	   		return "可用";
              	   	}else{
              	   		return "不可用";
              	   	}
      		   		
      	    }},
                  { display: '品牌', name: 'prodModel', width: 1,hide:true},
//                   { display: '<font color="gray">批次</font>', name: 'prodBatch', width: 80},
                  { display: '等级<font color="red">*</font>', name: 'status', width: 100
                	//<c:choose>
		           	    <c:when test="${'ADD' eq flag or '1'eq soreturn.billstatus or '5' eq soreturn.billstatus}">
                	  ,editor: { type: 'select', data: ItemStateList, valueColumnName: 'ItemStateID', displayColumnName: 'ItemStateName'},
      				 render: function (item){
      		        for (var i = 0; i < ItemStateList.length; i++){
      		        	if (ItemStateList[i]['ItemStateID'] == item.status){
      		          	  	return ItemStateList[i]['ItemStateName'];
      		            }
      		        }
      				return item.status;
      				}
                	  </c:when>
						<c:otherwise>
						,render: function (item){
							 var state=item.status;
			           		  if(state=="1"){
			           			  return "一等品";
			           		  }
			           		  if(state=="2"){
			           			  return "次品";
			           		  }
			           		  if(state=="3"){
			           			  return "旧件";
			           		  }
							}
						</c:otherwise>
						</c:choose>
      			  },
      			  { display: '<font color="gray">单价</font>', name: 'prodPrice', width:1 ,hide:true},
                  { display: '<font color="gray">基本单位</font>', name: 'prodBUnit', width: 80},
                  { display: '<font color="gray">单位换算率</font>', name: 'prodUnitConvert', width: 80},
                  { display: '<font color="gray">单位</font>', name: 'prodUnit', width: 80},
                  
                  {display : '<font color="gray">本次可退货数量</font>',name : 'tmpCanThQuantity',width : 100
						,render:function(item){
							item.tmpCanThQuantity =
								item.prodSfquantity - item.ytQuantity;
							return item.tmpCanThQuantity+"";
						  }
				  },

                  { display: '本次退货数量<font color="red">*</font>', name: 'sqthQuantity', width: 100
                  	//<c:if test="${'ADD' eq flag or '1'eq soreturn.billstatus or '5' eq soreturn.billstatus}">
                  	  ,editor: { type: 'float'},
                  	  render: function (item){
                  		//计算基本单位数量 parseFloat()
                  		if(item.openBatch=="Y"){
                  			item.sqthQuantity=item.val;
                  		}else{
	                  			 if(!isNaN(item.sqthQuantity) && !isNaN(item.prodUnitConvert)){
	                       	    	item.sqthBQuantity = item.sqthQuantity*item.prodUnitConvert ;
	                       	    }else{
	                       	    	item.sqthBQuantity=null;//清除值
	                       	    }
                  			}
                  			
                  		return item.sqthQuantity;
                  	  }
                  	//</c:if>
                    },
                  { display: '<font color="gray">退货基本单位数量</font>', name: 'sqthBQuantity', width: 110},
  				  { display: '总出库数量', name: 'ckQuantity', width: 1 ,hide:true},
                  { display: '<font color="gray">发货数量</font>', name: 'prodSfquantity', width: 80},
                  { display: '发货基本单位数量', name: 'prodBSfquantity', width: 1 ,hide:true},
                  { display: '<font color="gray">已退货数量</font>', name: 'ytQuantity', width: 100},
                  { display: '已退货基本单位数量', name: 'ytBQuantity', width: 1 ,hide:true},
                  { display : '销售含税单价',name : 'prodPriceWithTax',width : 1,hide:true}, 
				  { display : '销售金额',name : 'prodSum',width : 1,hide:true},
				  { display : '单据类型',name : 'sourceBillType',width : 100,render:function(item){
					  if(item.sourceBillType==1){
						  return "普通库存";
					  }else if(item.sourceBillType==2){
						  return "冻结库存";
					  }
				  }},
				  { display: '<font color="gray">值</font>', name: 'val' ,width:1,hide:1},
				  { display : '修改状态',name : 'updstatus',width:1,hide:1},
				  { display : '批次明细',name : 'itemBatch',width:1,hide:1},
                  { display: '备注', name: 'remark', width: 100
					//<c:if test="${'ADD' eq flag or '1'eq soreturn.billstatus or '5' eq soreturn.billstatus}">
					  ,editor: { type: 'text'}
					//</c:if>
				  }
                  ],
                  enabledEdit: true,
                  usePager: true,pageSize:1000,pageSizeOptions:[1000],
                  parms:[{ name : 'id' , value : '${soreturn.id}'}],
                  url : basic_Url+"/griditems.do",
                  width: "100%", height:320, checkbox: true
                //<c:if test="${'ADD' eq flag or '1'eq soreturn.billstatus or '5' eq soreturn.billstatus}">
					,toolbar: { items: [
                                     { text: '删除', click: deleteRow, img: '${ctx}/js/ligerUI/skins/icons/delete.gif' }
                                     ]
                             }
				//</c:if>
       });
	
	//表格数据添加
	/* var manager = $("#table1").ligerGetGridManager();
	//<c:forEach items='${returnitem}' var='item'>
    	manager.addRow2({
    		id: "${item.id}",
    		prodNo: "${item.prodNo}",
    		prodName: "${item.prodName}",
    		prodBatch: "${item.prodBatch}",
    		prodModel: "${item.prodModel}",
    		prodPrice: "${item.prodPrice}",
			prodPriceWithTax : "${item.prodPriceWithTax}",
			prodSum : "${item.prodSum}",
    		prodBUnit : "${item.prodBUnit}",
    		prodUnit : "${item.prodUnit}",
    		status : "${item.status}",
    		prodUnitConvert : "${item.prodUnitConvert}",
    		prodSpecDesc : "${item.prodSpecDesc}",
    		ckQuantity : "${item.ckQuantity}",
    		ytQuantity : "${item.ytQuantity}",
    		ytBQuantity : "${item.ytBQuantity}",
    		sqthQuantity : "${item.sqthQuantity}",
    		sqthBQuantity : "${item.sqthBQuantity}",
    		prodBSfquantity : "${item.prodBSfquantity}",
    		prodSfquantity : "${item.prodSfquantity}",
    		remark : "${item.remark}",
    		sourceBillType : "${item.sourceBillType}",
    		updstatus : "${item.updstatus}",
    		itemBatch : '${item.itemBatch}',
    		openBatch: "${item.openBatch}",
    		val : "${item.val}"
        });
    //</c:forEach> */
    
	//表格提交前验证
	$("#inputForm").validate({			   
	onsubmit: true,
	 /*执行ajaxsubmit  */ 
    submitHandler: function(editform) {
        try{			    		
            url =  basic_Url+"/save.do";
            var api = frameElement.api;
        	var W = api.opener;
            getReturnMessage(url,"inputForm",W.searchAP);
        }catch(e){alert(e);}
    }
	});

	//隐藏单元格
	if ('${flag}' == 'EDIT'){
	}else if ('${flag}' == 'ADD'){
		 $("#tr1").hide();
	}
	
	//按钮处理
	/* btn status */
	$("[id^='btn_fb_']").hide();
	var curStatus = "${soreturn.billstatus}";//当前所在环节、状态
	if(curStatus == ''){//建单
		$("#btn_fb_save").show();
	}else {
		$("#btn_fb_exportExcel").show();
		formComponentDisabled(true);//禁用控件
		if (curStatus == '1'||curStatus == '5'){//草稿状态-提交二级
			
			if("${user.name}"=="${soreturn.dcruser}"){
				$("#btn_fb_approve_2").show();
				$("#btn_fb_cancel").show();
			}
			formComponentDisabled(false);//启用控件
		}else if (curStatus == '2'){//二级审批中状态
			$("#btn_fb_rebut_2").show();
			$("#btn_fb_end_2").show();
		}else if (curStatus == '3'){//完结
			
		}else{
			
		}
	}
	
	//页面加载信息隐藏
	$("#pageloading").hide();
	
	//=============================

	//仓库下拉选择触发
	$("#storage").change(function(){ 
		var data = grid.getData();
		var code="";
		if (data.length == 0) {
			$.dialog.alert("请选择仓库");
			return false;
		}else{
			for(var i=0;i<data.length;i++){
				if(i==0){
					code=data[i].code;
				}else{
					code+=","+data[i].code;
				}
			}
		}
		  $("#whcode").val($("#storage").val());
		  $("#whname").val($("#storage").find("option:selected").text());//alert($("#storage").text());
		  
	}); 
	
	//销售订单编码下拉列表触发
	$("#selSoNo").change(function(){ 
		var selSoNo = $(this).val();
		
		$("#soNo").val(selSoNo);
		
		$.ajax({
		      url: basic_Url+"/getsowarelistCanReturnBySoNo.do",
		      global: false,
		      type: "POST",
		      dataType: "json",
		      data: ({
		    	soNo : selSoNo
		      }), 
		      success: function(o){
		    	  $("#po").empty();
		    	  var ls = o.list;
		    	  $("#po").append("<option value=''></option>");   
		    	  for(var i=0;i<ls.length;i++){
		    		  var tmpItem = ls[i];
		    		  $("#po").append("<option value='"+tmpItem.id+"'>"+tmpItem.no+"</option>");   
		    	  }
		    	  
		    	  $("#po").val("${soreturn.oricode}");
		    	  
		    	  
		    	  $("#po").change(function(){
		    		   $("#cliName").val("");
						$("#cliNo").val("");
						
		        		$("#storage").val("");
		        		$("#whname").val("");
		        		$("#whcode").val("");
		        		
		        		$("#currency").val("");
		        		$("#exchangeRate").val("");
		        		
		    		  var tmpVal = $(this).val();
		    			if(tmpVal!=''){
		    				$("#oricode").val($(this).find("option:selected").text());
		    				
		    				for(var i=0;i < ls.length;i++){
		    					var tmpItem = ls[i];
		    					if(tmpVal==tmpItem.id){
		    						$("#cliName").val(tmpItem.cliName);
		    						$("#cliNo").val(tmpItem.cliNo);
		    						
		    		        		$("#storage").val(tmpItem.whcode);
		    		        		$("#whname").val(tmpItem.whname);
		    		        		$("#whcode").val(tmpItem.whcode);
		    		        		
		    		        		$("#currency").val(tmpItem.currency);
		    		        		$("#exchangeRate").val(tmpItem.exchangeRate);
		    		        		
		    					}
		    				}
		    				
		    				multipleSearch("#table1",true,"",basic_Url+"/sowareitemlist.do?sowareid="+tmpVal);
		    			}
		    		});
		      }
	   });
	});
	

});

//表单提交处理
function submitForm(param){
    //设置ajax全局同步
	//var data = JSON.stringify(grid.getData());
	var data = grid.getData();
	if(data.length==0){
		$.dialog.alert("请选择物料");
   	 	return false;
	}
	
	var ba=true;
	if(data !=null){
		var j=0;
		$(data).each(function (){
			j++;
			//表格必填项
			
			if (undefined == this.sqthQuantity
					|| isNaN(this.sqthQuantity)
					|| this.sqthQuantity <= 0) {
				$.dialog.alert("第" + j + "行的“本次退货数量”数据不合法");
				ba = false;
				return false;
			}
			
			if (undefined == this.sqthBQuantity
					|| isNaN(this.sqthBQuantity)
					|| this.sqthBQuantity <= 0) {
				$.dialog.alert("第" + j + "行的“本次退货基本单位数量”数据不合法");
				ba = false;
				return false;
			}
			if(/* (this.prodSfquantity-this.ytQuantity) */
					this.tmpCanThQuantity < this.sqthQuantity){
				$.dialog.alert("您第" + j + "的退货数量大于出库单据的出库数量");
				ba = false;
				return false;
			}


			});
	}
	jQuery.ajaxSettings.async = false;
		if (ba) {
			$("#itemdata").val(JSON.stringify(data));
			$("#submitFlag").val(param);
			formComponentDisabled(false);//启用控件
			$("#inputForm").submit();
		}
}

function tableSubmit(msg,param){
	$.ligerDialog.confirm(msg, 
			function (flag) { 
			if(flag){
				submitForm(param);
				}
		}); 
}

function submitFormClose(param){
	tableSubmit('是否确认关闭单据操作？',param);
}

function submitFormEnd(param){
	tableSubmit('是否确认审批完结操作？',param);
}

function submitFormRebut(param){
	tableSubmit('是否确认驳回操作？',param);
}

	function deleteRow() {
		grid.deleteSelectedRow();
	}
	
	function ItemWindow(rc,index) {
	 	var manager = $("#table1").ligerGetGridManager();
			getDG().dialog(
					{
						title : '批次管理',
						width : 650,
						height : 350,
						content : 'url:' + sys_context+ '/yd/logic/soreturn/itemManager.do?data='+encodeURIComponent(JSON.stringify(manager.getRow(rc.__index)))+'&billstatus=${soreturn.billstatus}'+'&updstatus='+rc.updstatus,//
						lock : true,
						max : true,
						min : true,
						ok : function() {
							this.content.yz();
							if(this.content.ba){
							var dt = this.content.grid.getData();
							if (dt != null) {
								rc.sqthBQuantity=this.content.jnum;
								rc.sqthQuantity=this.content.num;
								rc.val=this.content.num;
								rc.updstatus=1;
								rc.itemBatch=JSON.stringify(dt);
										grid.updateCell('sqthBQuantity', rc.sqthBQuantity, manager.getRow(rc.__index));
										grid.updateCell('sqthQuantity', rc.sqthQuantity, manager.getRow(rc.__index));
										grid.updateCell('val', rc.val, manager.getRow(rc.__index));
										grid.updateCell('itemBatch',rc.itemBatch, manager.getRow(rc.__index));
										grid.updateCell('updstatus', rc.updstatus, manager.getRow(rc.__index));
										grid.updateRow(manager.getRow(rc.__index));
										this.content.Close();
								}else{
									this.content.Close();
								}
								
							}
							return false;
						},
						cancelVal : '关闭',
						cancel : true
					}).zindex();
		}
</script>

</head>

<body>

<form id="inputForm" action="" method="post">
<input type="hidden" id="id" name="id" value="${soreturn.id}"/>
<input type="hidden" id="version" name="version" value="${soreturn.version}"/>
<input type="hidden" id="itemdata" name="itemdata" value=""/>
<!-- 用于标识提交按钮 -->
<input type="hidden" id="submitFlag" name="submitFlag" value="" />

<input type="hidden" id="exchangeRate" name="exchangeRate" value="${soreturn.exchangeRate}" /><!-- 汇率 -->
<input type="hidden" id="currency" name="currency" value="${soreturn.currency}"/><!-- 币别 -->
 <div class="pageContent" >
    <div class="panel">
         <table class="TableBlock" align="center">
   		           <tr id="tr1">
   		           		<td nowrap="nowrap">单据编号:</td>
   		           		<td>
   		                	<input type="text" id="returnsocode" name="returnsocode" readonly="readonly" class="inp_width_98p required" value="${soreturn.returnsocode}" />
   		                </td>
   		                <td nowrap="nowrap">建单时间:</td>
   		                <td><input type="text" id="dctime" name="dctime" class="inp_width_98p"
							value="<fmt:formatDate value="${empty soreturn.dctime?nowDate:soreturn.dctime}" type="both" dateStyle="long" pattern="yyyy-MM-dd" />" readonly="readonly"/>
						</td>
   		           </tr>
   		           <tr>
   		           		<td nowrap="nowrap">销售订单编号:</td>
   		           		<td>
   		           		<c:choose>
   		           		<c:when test="${'ADD' eq flag}">
   		           			<select id="selSoNo" name="selSoNo" class="inp_width_98p required">
   		                 	<option></option>
   		                 	<c:forEach items='${solist}' var='state'>
   		                 	<option value='${state.no}'>${state.no}</option>
   		                 	</c:forEach>
   		                 	</select>
   		                 	<input type="hidden" id="soNo" name="soNo" value="${soreturn.soNo}"/>
   		                 	<script type="text/javascript">
   		                		 $("#selSoNo").val("${soreturn.soNo}");
   		                 	</script>
   		           		</c:when>
   		           		<c:otherwise>
   		           		<input type="text" class="inp_width_98p" readonly="readonly" id="soNo" name="soNo" value="${soreturn.soNo}"/>
   		           		</c:otherwise>
   		           		</c:choose>
   		                </td>
   		                <td nowrap="nowrap">出库单编号:</td>
   		                <td>
   		                <c:choose>
   		           		<c:when test="${'ADD' eq flag }">
   		           			<select id="po" name="po" class="inp_width_98p required"></select>
   		                 	<input type="hidden" id="oricode" name="oricode" value="${soreturn.oricode}"/>
   		                 	<!-- <script type="text/javascript">
   		                		 $("#po").val("${soreturn.oricode}");
   		                 	</script> -->
   		           		</c:when>
   		           		<c:otherwise>
   		           		<input type="text" class="inp_width_98p" readonly="readonly" id="oricode" name="oricode" value="${soreturn.oricode}"/>
   		           		</c:otherwise>
   		           		</c:choose>
   		                 
   		                 </td>
						<%-- <td nowrap="nowrap">制单人:</td>
                    	<td>
   		                 	<input type="text" class="inp_width_98p required" id="listerName" name="listerName" value="${soreturn.listerName}" readonly="readonly"/>
   		                 </td> --%>
   		           </tr>
   		           <tr>
   		           		<td nowrap="nowrap">退货仓库:</td>
                    	<td>
   		                <c:choose>
   		           		<c:when test="${'ADD' eq flag or '1'eq soreturn.billstatus or '5' eq soreturn.billstatus}">
							<select id="storage" name="storage" class="inp_width_98p required">
   		                 	<option></option>
   		                 	<c:forEach items='${wh}' var='state'>
   		                 	<option value='${state.code}'>${state.name}</option>
   		                 	</c:forEach>
   		                 	</select>
   		                 	<script type="text/javascript">
   		                		$("#storage").val("${soreturn.whcode}");
   		                 	</script>
   		                 	
   		                </c:when>
						<c:otherwise>
						<input type="text" value="${soreturn.whname}" id="storage" name="storage" class="inp_width_98p"  readonly="readonly"></input>
						</c:otherwise>
						</c:choose>
						
						<input type="hidden" id="whcode" name="whcode" value="${soreturn.whcode}"/>
   		                <input type="hidden" id="whname" name="whname" value="${soreturn.whname}"/>
   		                 </td>
   		                 <td nowrap="nowrap">退货日期:</td>
    		                 <td>
   		               		 <input type="text" id="returnDate" name="returnDate" onclick="WdatePicker({dateFmt:'yyyy-MM-dd'})" class="inp_width_98p required" value="<fmt:formatDate value="${soreturn.returnDate}" pattern="yyyy-MM-dd" type="both" />"  readonly="readonly"/>
   		                 </td>
   		           </tr>
   		            <tr>
   		            <td nowrap="nowrap">退货单位编号</td>
   		            <td><input type="text" readonly="readonly" class="inp_width_98p required" id="cliNo" name="cliNo" value="${soreturn.cliNo}"/>
   		            </td>
   		            <td nowrap="nowrap">退货单位名称:</td>
   		            <td><input type="text" readonly="readonly" class="inp_width_98p required" id="cliName" name="cliName" value="${soreturn.cliName}"/>
   		            </td>
   		           </tr>
   		           <tr>
   		           	<td nowrap="nowrap">退货原因:</td>
   		           	<td colspan="3"><input id="remark" name="remark" value="${soreturn.remark}" class="inp_width_98p"/></td>
   		           </tr>
                </table>
                <div id="table1"> </div>               
         </div>
         <div class="formBar">
	        <ul>
		       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="btn_fb_save" onclick="submitForm(1)">保存</button></div></div></li>
		       
		       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="btn_fb_approve_2" onclick="submitForm(2)" title="提交二级审核">提交</button></div></div></li>
		       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="btn_fb_cancel" onclick="submitFormClose(4)" title="取消订单">取消</button></div></div></li>
		      
		       <webres:displaycontroller elementId="LOGIC_SORETURN_2WANJIE" description="销售退货二级完结">
		       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="btn_fb_end_2" onclick="submitFormEnd(3)" title="二级结案">审核</button></div></div></li>
		       </webres:displaycontroller>
		       <webres:displaycontroller elementId="LOGIC_SORETURN_2BOHUI" description="销售退货二级驳回">
		       <li><div class="button"><div class="buttonContent"><button type="button" id="btn_fb_rebut_2" onclick="submitFormRebut(5)" title="二级驳回到草稿">驳回</button></div></div></li>
		       </webres:displaycontroller>
		       
		       <li><div class="button"><div class="buttonContent"><button type="button" class="print" onclick="CloseDialog()">关闭</button></div></div></li>
	        </ul>
        </div>    
    </div>
</form>
</body>
</html>
